﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Nizm0.QOT.Library.Controls
{
    /// <summary>
    /// Interaction logic for ProcedureListObject.xaml
    /// </summary>
    [Serializable]
    public partial class ProcedureListObject : ListBoxItem
    {
        public Objects.ProcedureInfo Procedure;

        //private ProgressBar progress = new ProgressBar();

        public ProcedureListObject(Objects.ProcedureInfo procedure)
        {
            InitializeComponent();
            Procedure = procedure;
            text.Text = procedure.Name;
            Name = procedure.Name;
            checkBox_looking.IsChecked = procedure.Looking;
            if (procedure.ResultList.Count != 0)
                counter.Content = procedure.ResultList.Count;
            else
                counter.Content = procedure.Found;

            procedure.StatusChange += new Objects.ProcedureInfo.EventOnStatusChange(procedure_StatusChange);
            OnStatusChange(this, procedure.QuerySearchingStatus);
            procedure.NewQuedyAdd += new Objects.ProcedureInfo.NewQuedyAddHandler(procedure_NewQuedyAdd);

            //Objects.ProcedureInfo.SetEventOnLookingChange(LookingValueChanged);
            procedure.LookingValueChanged += LookingValueChanged;
        }

        ~ProcedureListObject()
        {
            try
            {
                this.Procedure.StatusChange -= procedure_StatusChange;
                this.Procedure.NewQuedyAdd -= procedure_NewQuedyAdd;
                this.Procedure.LookingValueChanged -= LookingValueChanged;
            }
            catch
            {
            }
        }

        public delegate void EventStatusChange(object sender, Objects.ProcedureInfo.Status e);
        public event EventStatusChange StatusChange;

        private void procedure_StatusChange(object sender, Objects.ProcedureInfo.Status e)
        {
            if (StatusChange == null)
                StatusChange += OnStatusChange;
            Dispatcher.BeginInvoke(StatusChange, sender, e);
        }

        private void OnStatusChange(object sender, Objects.ProcedureInfo.Status e)
        {
            switch (e)
            {
                case Objects.ProcedureInfo.Status.Error:
                    {
                        this.Background = new SolidColorBrush(Colors.Red);
                        break;
                    }
                case Objects.ProcedureInfo.Status.Started:
                    {
                        this.Progress.Visibility = Visibility.Visible;
                        this.checkBox_looking.Visibility = System.Windows.Visibility.Hidden;
                        this.Background = new SolidColorBrush(Colors.Yellow);
                        break;
                    }
                case Objects.ProcedureInfo.Status.Ended:
                    {
                        this.Progress.Visibility = Visibility.Hidden;
                        this.checkBox_looking.Visibility = System.Windows.Visibility.Visible;
                        this.Background = new SolidColorBrush(Colors.LightGreen);
                        break;
                    }
                case Objects.ProcedureInfo.Status.Opened:
                    {
                        this.Background = new SolidColorBrush(Colors.LightGray);
                        break;
                    }
                case Objects.ProcedureInfo.Status.Ready:
                    {
                        this.Background = new SolidColorBrush(Colors.LightSeaGreen);
                        break;
                    }
                default:
                    {
                        this.Background = new SolidColorBrush(Colors.LightBlue);
                        break;
                    }
            }

        }

        public void LookingValueChanged(object sender, bool e)
        {
            this.Dispatcher.Invoke((Action)delegate
            {
                Library.Objects.ProcedureInfo tmpproc = (Library.Objects.ProcedureInfo)sender;
                if (object.ReferenceEquals(tmpproc, Procedure))
                    checkBox_looking.IsChecked = e;
            });
        }

        private void procedure_NewQuedyAdd(object sender, NewQueryFoundEventArgs e)
        {
            this.Dispatcher.Invoke((Action)delegate
            {
                counter.Content = ((Objects.ProcedureInfo)e.Procedure).ResultList.Count;
            });
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

        }

        public void HideCheckBox()
        {
            checkBox_looking.Visibility = System.Windows.Visibility.Hidden;
        }

        public void ShowCheckBox()
        {
            checkBox_looking.Visibility = System.Windows.Visibility.Visible;
        }

        private void MenuItem_ShowResult_Click(object sender, RoutedEventArgs e)
        {
            Procedure.OpenResultFile();
        }

        private void MenuItem_OpenFolder_Click(object sender, RoutedEventArgs e)
        {
            string directory;

            if (System.IO.File.Exists(Procedure.ResultFile))
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(Procedure.ResultFile);
                directory = fi.DirectoryName;
            }
            else
            {
                directory = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
            }
            if (System.IO.Directory.Exists(directory))
            {
                string myPath = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
                string myFile = myPath + "\\" + Procedure.Name + ".txt";
                System.Diagnostics.Process prc = new System.Diagnostics.Process();
                //if (System.IO.File.Exists(myFile))
                //{
                //    prc.StartInfo.FileName = myFile;
                //}
                //else
                prc.StartInfo.FileName = myPath;
                prc.Start();
                //string myDocspath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                //string windir = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
                //System.Diagnostics.Process prc = new System.Diagnostics.Process();
                //prc.StartInfo.FileName = windir + @"\explorer.exe";
                //prc.StartInfo.Arguments = myDocspath;
                //prc.Start();
                ////System.Diagnostics.Process.Start("explorer.exe", Library.Objects.ProjectSettings.Instance.ProjectResultsLocation);
            }
            else
            {
                //_project.Procedures[dataGridView_LookingProcedures.SelectedRows[0].Cells[Procedures.Name].Value].
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        public void OpenResultCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            Procedure.OpenResultFile();
        }

        public void CanOpenResultExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            if (sender != null && !string.IsNullOrWhiteSpace(Procedure.ResultFile) && System.IO.File.Exists(Procedure.ResultFile))
                e.CanExecute = true;
        }

        public void OpenFileLocationCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            Procedure.OpenFileLocation();
            //string directory;

            //if (System.IO.File.Exists(Procedure.ResultFile))
            //{
            //    System.IO.FileInfo fi = new System.IO.FileInfo(Procedure.ResultFile);
            //    directory = fi.DirectoryName;
            //}
            //else
            //{
            //    directory = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
            //}
            //if (System.IO.Directory.Exists(directory))
            //{
            //    string myPath = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
            //    string myFile = myPath + "\\" + Procedure.Name + ".txt";
            //    System.Diagnostics.Process prc = new System.Diagnostics.Process();
            //    prc.StartInfo.FileName = myPath;
            //    prc.Start();
            //}
            //else
            //{
            //    //_project.Procedures[dataGridView_LookingProcedures.SelectedRows[0].Cells[Procedures.Name].Value].
            //}
        }

        public void CanOpenFileLocationExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            if (sender != null && !string.IsNullOrWhiteSpace(Procedure.ResultFile) && System.IO.Directory.Exists(new System.IO.FileInfo(Procedure.ResultFile).DirectoryName))
                e.CanExecute = true;
        }
        
        private void checkBox_looking_Checked(object sender, RoutedEventArgs e)
        {
            if (Procedure.Looking != checkBox_looking.IsChecked.Value)
                Procedure.Looking = checkBox_looking.IsChecked.Value;
        }

        private void expand_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            System.Threading.Thread.Sleep(1);
        }
        
        /*private void MenuItem_Cut_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            //    string text = string.Empty;
            //    List<Objects.IProcedureInfo> list = new List<Objects.IProcedureInfo>();

            //    System.Windows.Clipboard.Clear();
            //    //ListBox.SelectedObjectCollection tmpList = listBox_Procedury.SelectedItems;
            //    foreach (Library.Objects.IProcedureInfo tmpprocedure in this.SelectedItems)
            //    {
            //        text += tmpprocedure.Name;
            //        text += "\r\n";
            //        list.Add(tmpprocedure);
            //    }

            //    //TODO collection of temporary remowed object ProcedureResultInformation
            //    //Clipboard.SetData("SelectedObjectCollection", listBox_Procedury.SelectedItems);

            //    //foreach (Library.Objects.ProcedureInfo ip in listBox_Procedury.SelectedItems)
            //    //{
            //    //    list.Add(ip);
            //    //}

            //    System.Windows.Clipboard.SetData("listBox_Procedury.SelectedItems", Serialize(list));//.SetData("SelectedObjectCollection", listBox_Procedury.SelectedItems);


            //    //var deslist = DeSerialize(Clipboard.GetData("listBox_Procedury.SelectedItems").ToString());
            //    //Clipboard.SetDataObject(list);

            //    //Clipboard.SetText(text);


            //    int a = this.SelectedItems.Count;

            //    for (int index = 0; index < a; index++)
            //    {
            //        //NewEventDeleteProcedure((Library.Objects.ProcedureInfo)Library.Objects.ProjectSettings.Instance.ProceduresList.Find(p => p == listBox_Procedury.SelectedItems[0]));
            //        Library.Objects.ProjectSettings.Instance.RemoweProcedure((Library.Objects.IProcedureInfo)this.SelectedItems[index]);//.Remove(ProjectSettings.ProceduresList.Find(p=>p==listBox_Procedury.SelectedItems[0]));
            //        ((CurrencyManager)this.BindingContext[this.DataSource]).Refresh();
            //        //listBox_Procedury.Items.Remove(listBox_Procedury.SelectedItems[0]);
            //    }
            //    //NotSaved();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, ex.Source);
            //    if (ErrorEvent != null)
            //    {
            //        ErrorEvent(this, ex);
            //    }
            //}
        }

        private void MenuItem_Copy_Click(object sender, RoutedEventArgs e)
        {
            //string text = string.Empty;
            //System.Windows.Clipboard.Clear();
            //for (int i = 0; i < this.SelectedItems.Count; i++)
            //{
            //    text += this.SelectedItems[i].ToString();
            //    text += "\r\n";
            //}
            ////MessageBox.Show(text);
            //System.Windows.Clipboard.SetText(text);
            ////MessageBox.Show(Clipboard.GetText());
        }

        private void MenuItem_Delete_Click(object sender, RoutedEventArgs e)
        {
            Settings.Instance.ProjectSettings.ProceduresList.Remove(Procedure);
            ((ListBox)this.Parent).Items.Remove(this);
            //try
            //{
            //    for (int index = 0; index < this.SelectedItems.Count; index++)
            //    {
            //        //Library.Objects.ProjectSettings.Instance.RemoweProcedure((Library.Objects.IProcedureInfo)this.SelectedItems[index]);
            //        //((CurrencyManager)this.BindingContext[this.DataSource]).Refresh();



            //        //((ProcedureListObject)this.SelectedItems[index]).Procedure
            //        Remove(((ProcedureListObject)this.SelectedItems[index]).Procedure);

            //    }
            //    //textbox_Informacje.Clear();
            //}
            //catch (Exception ex)
            //{
            //    //MessageBox.Show(ex.Message, ex.Source);
            //    //if (ErrorEvent != null)
            //    //{
            //    //    ErrorEvent(this, ex);
            //    //}
            //}
        }

        private void MenuItem_Refresh_Click(object sender, RoutedEventArgs e)
        {
            //ListBox tmplistbox = (ListBox)sender;
            //foreach (Objects.ProcedureInfo tmpproc in this.SelectedItems)
            //{
            //    Library.Objects.ProjectSettings.Instance.GetDataAboutProcedure(tmpproc);
            //}
        }

        private void MenuItem_Properties_Click(object sender, RoutedEventArgs e)
        {

        }

        private void CanCopyExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            //System.Threading.Thread.Sleep(1);
            if (sender != null)
                e.CanExecute = true;
        }

        private void CopyCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            ListBox lb = (ListBox)(sender);
            var selected = lb.SelectedItems;
            
            //List<Objects.ProcedureInfo> olist = new List<Objects.ProcedureInfo>();
            //olist.Add(this.Procedure);
            Settings.Instance.ProjectSettings.CopyProcedures(new List<Objects.ProcedureInfo>((IEnumerable<Objects.ProcedureInfo>)selected));
        }

        private void OpenResultCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            Procedure.OpenResultFile();
        }

        private void CanOpenResultExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            //System.Threading.Thread.Sleep(1);
            if (sender != null && !string.IsNullOrWhiteSpace(Procedure.ResultFile) && System.IO.File.Exists(Procedure.ResultFile))
                e.CanExecute = true;
        }

        private void OpenFileLocationCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            string directory;

            if (System.IO.File.Exists(Procedure.ResultFile))
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(Procedure.ResultFile);
                directory = fi.DirectoryName;
            }
            else
            {
                directory = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
            }
            if (System.IO.Directory.Exists(directory))
            {
                string myPath = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
                string myFile = myPath + "\\" + Procedure.Name + ".txt";
                System.Diagnostics.Process prc = new System.Diagnostics.Process();
                //if (System.IO.File.Exists(myFile))
                //{
                //    prc.StartInfo.FileName = myFile;
                //}
                //else
                prc.StartInfo.FileName = myPath;
                prc.Start();
                //string myDocspath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                //string windir = Library.Objects.ProjectSettings.Instance.ProjectResultsLocation;
                //System.Diagnostics.Process prc = new System.Diagnostics.Process();
                //prc.StartInfo.FileName = windir + @"\explorer.exe";
                //prc.StartInfo.Arguments = myDocspath;
                //prc.Start();
                ////System.Diagnostics.Process.Start("explorer.exe", Library.Objects.ProjectSettings.Instance.ProjectResultsLocation);
            }
            else
            {
                //_project.Procedures[dataGridView_LookingProcedures.SelectedRows[0].Cells[Procedures.Name].Value].
            }
        }

        private void CanOpenFileLocationExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            //System.Threading.Thread.Sleep(1);
            if (sender != null && !string.IsNullOrWhiteSpace(Procedure.ResultFile) && System.IO.Directory.Exists(new System.IO.FileInfo(Procedure.ResultFile).DirectoryName))
                e.CanExecute = true;
        }

        private void CanPasteExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
        {
            if (sender != null && (System.Windows.Clipboard.ContainsText() || System.Windows.Clipboard.ContainsData("List<Objects.ProcedureInfo>")))
                e.CanExecute = true;
        }

        private void PasteCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            Settings.Instance.ProjectSettings.AddProcedureFromClipboard();
        }
        */
    }

    public static class Command
    {
        public static readonly RoutedUICommand OpenResult = new RoutedUICommand("Open Result", "OpenResult", typeof(ListBoxItem));
        public static readonly RoutedUICommand OpenFileLocation = new RoutedUICommand("Open file location", "OpenFileLocation", typeof(ListBoxItem));
    }
}
